#!/bin/bash
export TZ=Asia/Shanghai
shopt -s expand_aliases
[ "$(uname)" == "Darwin" ] &&  alias date='gdate'

PROGRESS_ARGS=""

YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)
echo YESTERDAY=$YESTERDAY

while getopts "t:P" opt; do
    case ${opt} in
        t )
        DATE="$OPTARG"
        ;;
        P )
        PROGRESS_ARGS="--progress"
        ;;
        *)
        echo "Invalid option: $opt requires an argument" 1>&2
        ;;
    esac
done
shift $((OPTIND -1))
DATE=$(date -d "$YESTERDAY" +%Y%m%d)
YEAR_MONTH=$(date -d "$YESTERDAY" +%Y%m)
DAY=$(date -d "$YESTERDAY" +%d)
echo DATE=$DATE, YEAR_MONTH=$YEAR_MONTH, DAY=$DAY
mkdir -p /sftp_data/logs/$YEAR_MONTH
LOG_FILE=/sftp_data/logs/$YEAR_MONTH/rclone-$DAY.log
date >> $LOG_FILE
echo "begin syncing DATE=$DATE" >> $LOG_FILE
mkdir -p /sftp_data/sftp_bbw_ro/home/$DATE

rclone --log-file=$LOG_FILE --log-level INFO copy aiphq-sftp-bbw:/beibugulfbank/$DATE /sftp_data/sftp_bbw_ro/tmp/$DATE/ || echo "error"
iconv -f utf8 -t gb18030 /sftp_data/sftp_bbw_ro/tmp/$DATE/tlbh_merc_$DATE.csv > /sftp_data/sftp_bbw_ro/home/$DATE/tlbh_merc_$DATE.csv
iconv -f utf8 -t gb18030 /sftp_data/sftp_bbw_ro/tmp/$DATE/tlbh_txn_$DATE.csv > /sftp_data/sftp_bbw_ro/home/$DATE/tlbh_txn_$DATE.csv
touch  ok_$DATE.ok

cp /sftp_data/sftp_bbw_ro/tmp/$DATE/ok_$DATE.ok /sftp_data/sftp_bbw_ro/home/$DATE/
rm -fr /sftp_data/sftp_bbw_ro/tmp/$DATE
echo "sync completed" >> $LOG_FILE